const gulp = require("gulp");
const connect = require("gulp-connect");
const htmlmin = require("gulp-htmlmin");
const uglify = require("gulp-uglify");
const babel = require("gulp-babel");
const sass = require("gulp-sass")(require('sass'));
const cssmin = require("gulp-cssmin");


gulp.task("sayhi", async() => {
        console.log("hello gulp");
    })
    //开启服务器
gulp.task("connect", async() => {
        connect.server({
            //自动刷新
            livereload: true,
        });
    })
    //将源码放入dist转义的文件夹中

gulp.task("html", async() => {
    gulp.src(["./src/**/*.html"])
        .pipe(gulp.dest("./dist"))
        .pipe(connect.reload())

})

//压缩html
gulp.task("html-min", async() => {
    gulp.src(["./src/**/*.html"])
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest("./dist"))
        .pipe(connect.reload())
})

//转义js文件
gulp.task("javascripts", async() => {
        gulp.src(["./src/javascripts/**/*.js"])
            .pipe(gulp.dest("./dist/javascripts"))
            .pipe(connect.reload())
    })
    //压缩js文件
gulp.task("javascripts-min", async() => {
        gulp.src(["./src/javascripts/**/*.js"])
            .pipe(uglify())
            .pipe(gulp.dest("./dist/javascripts"))
            .pipe(connect.reload())
    })
    //将ES6-ES5   cnpm i  gulp-babel @babel/core @babel/preset-env --save
gulp.task("javascripts-babel", async() => {
        gulp.src(["./src/javascripts/**/*.js"])
            .pipe(babel({
                presets: ['@babel/env']
            }))
            .pipe(uglify())
            .pipe(gulp.dest("./dist/javascripts"))
            .pipe(connect.reload())
    })
    //转义css文件
gulp.task("scss", async() => {
        gulp.src(["./src/scss/**/*.scss"])
            .pipe(sass().on('error', sass.logError))
            .pipe(gulp.dest("./dist/css"))
            .pipe(connect.reload())
    })
    //压缩scss
gulp.task("scss-min", async() => {
        gulp.src(["./src/scss/**/*.scss"])
            .pipe(sass().on('error', sass.logError))
            .pipe(cssmin())
            .pipe(gulp.dest("./dist/css"))
            .pipe(connect.reload())
    })
    //监听
gulp.task("watch", async() => {
        gulp.watch(["./src/**/*.html"], gulp.parallel("html"));
        gulp.watch(["./src/javascripts/**/*.js"], gulp.parallel("javascripts"));
        gulp.watch(["./src/scss/**/*.scss"], gulp.parallel("scss"));

    })
    //同时开启监听和开启服务器
gulp.task("default", gulp.series("html", "scss", "javascripts", gulp.parallel("connect", "watch")));

//组合指令
gulp.task("build", gulp.series("html-min", "scss-min", "javascripts-min"));